package uit.edu.vn.Activity;


import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import uit.edu.vn.Model.FileObject;
import uit.edu.vn.Model.myFile;
import uit.edu.vn.Model.mySMS;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.WebService;
import uit.edu.vn.Utility.xStreamXML;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SmsRestoreServerActivity extends MyActivity {
	
	private TextView titleHeader;
	private ListView listview;
	private Context context;
	private Resources res;
	private String path=Environment.getExternalStorageDirectory()+"/BackupManager/SMS";
	private ArrayList<myFile> listFiles = new ArrayList<myFile>();
	private ArrayList<mySMS> listFileRestore= new ArrayList<mySMS>();
	private int numberOfItemSelected = 0;	
	private ArrayAdapter<myFile> arrayAdapter;
	private ArrayList<FileObject> flist = new ArrayList<FileObject>();
	private AESControl aes;	
	public int totalSize;
	public int len = 0;
	public InputStream in;
	public File output;
    private String urlString = null;
    private String userid = null;
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
    private int type = 2;
	private ProgressDialog loadingSmsDialog;
	
    @Override

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp"; 		
		
		setContentView(R.layout.backup_file);
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(SmsRestoreServerActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }
	      
	      System.out.println("SmsRestoreServerActivity");
	      System.out.println("username: "+ username);
	      System.out.println("password: "+ password);
	      System.out.println("userid:   "+ userid);
	      System.out.println("address:   "+ urlString);	     
	      System.out.println("MainActivity.address.toString() : " + MainActivity.address.toString());
		listview =(ListView) findViewById(R.id.listFileBackup);
        res=getResources();	
        context=getBaseContext();	
        titleHeader=(TextView)findViewById(R.id.txt_titleFile);
        titleHeader.setText(R.string.title_RestoreHeaderSmsServer);
		loadingSmsDialog= new ProgressDialog(this);
		loadingSmsDialog.setMessage("Đang tải dữ liệu");
		loadingSmsDialog.setCancelable(false);
		loadingSmsDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		CheckInternet chkI= new CheckInternet(context);
        if(chkI.checkStatus().equals(true))
		{

        	new BackgroundTask().execute();
        	
		}
        else
        {
        	Log.d("ketnoi", "ko co ket noi internet");
        	showToast("Không có kết nối");
        
        }
    	listview.setOnItemClickListener(new OnItemClickListener() 
        {
     	   @Override
     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,long arg3) {
     		   
     		   	try {
     		   		
							// TODO Auto-generated method stub

							myFile entry = listFiles.get(position);
							File temp = new File(entry.getPath());
							final Dialog dialog=new Dialog(SmsRestoreServerActivity.this);
			 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.file_dialog_server);
			 	    		dialog.setTitle("Thông tin tập tin ");
			 	    		TextView txt_filename= (TextView)dialog.findViewById(R.id.txt_filenameDialog);
			 	    		TextView txt_filesize= (TextView)dialog.findViewById(R.id.txt_filesizeDialog);
			 	    		TextView txt_fileday=(TextView)dialog.findViewById(R.id.txt_filedayDialog);
			 	    		String day=flist.get(position).dayBackupFile;
			 	    		txt_fileday.setText(day);
			 	    		txt_filename.setText(temp.getName());
			 	    		int size_temp=Integer.parseInt(entry.getSize());
			 	    		System.out.println(size_temp);
		                	if(size_temp<1024)
		                	{
		                		txt_filesize.setText(entry.getSize()+" Byte");   
		                	}
		                	else if(size_temp<1048576)
		                	{
		                		System.out.println(size_temp);
		                		size_temp=size_temp/1024;
		                		System.out.println(size_temp);
		                		txt_filesize.setText(size_temp+" KB"); 
		                	}
		                	else
		                	{
		                		size_temp=size_temp/1048576;
		                		txt_filesize.setText(size_temp+" MB"); 
		                	}
			 	    	
			 	    	//	txt_filesize.setText(entry.getSize()+"byte");
			 	    		
			 	    		Button btn_ok = (Button)dialog.findViewById(R.id.btn_okDialog);
			 	    		btn_ok.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			 	    		dialog.show();
						}
				
     		   	 catch (Exception e) {
					// TODO: handle exception
					  e.printStackTrace();
				}
     		   	
		
     	   }
        });
        }
    
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}     
    
   	private class BackgroundTask extends AsyncTask<Void, Void, Void>
    {
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    	
	        loadingSmsDialog.show();

    	}
    	@Override
    	protected Void doInBackground(Void... params) {
    		// TODO Auto-generated method stub
    		try {
        			flist = WebService.getAllList(Integer.parseInt(userid), type);
        			for(int i = 0;i<flist.size(); i++){
        				System.out.println("ten tap tin sms da sao luu: "+flist.get(i).getFileName());
        			}
        			convert(flist);//convert tu fileObject sang myFile
    			
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    		return null;
    	}
    	@Override
    	protected void onPostExecute(Void result) {
    		// TODO Auto-generated method stub
    		loadingSmsDialog.dismiss();
    		arrayAdapter = new ArrayAdapter<myFile>(context, R.layout.row_file, listFiles) {
	            @Override
	            public View getView(int position, View v, ViewGroup parent) {
	                if (v == null) {
	                    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                    v = vi.inflate(R.layout.row_file, null);
	                }
	                myFile ffile = listFiles.get(position);                
	                if(ffile!=null){
	                    TextView tx_fileName = (TextView)v.findViewById(R.id.txt_fileName);
	                    TextView tx_size = (TextView)v.findViewById(R.id.txt_filePath);
	                    ImageView iv = (ImageView) v.findViewById(R.id.img_fileIcon);
	                    iv.setImageDrawable(res.getDrawable(R.drawable.ic_text));
	                    
	                    CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chkSelectFile);
	                    chkSelect.setChecked(false);

	                	tx_fileName.setText(ffile.getName());
	                	int temp=Integer.parseInt(ffile.getSize());
	                	if(temp<1024)
	                	{
	                		tx_size.setText(ffile.getSize()+" Byte");   
	                	}
	                	else if(temp<1048576)
	                	{
	                		temp=temp/1024;
	                		tx_size.setText(temp+" KB"); 
	                	}
	                	else
	                	{
	                		temp=temp/1048576;
	                		tx_size.setText(temp+" MB"); 
	                	}
	                	
	                	}
	                return v;
	            }
			};

			countItemChecked();	 
			listview.setAdapter(arrayAdapter);

			super.onPostExecute(result);
    	}
    }


	//---------------------------xu ly menu----------------------------------
	// tao menu option 
		public boolean onCreateOptionsMenu(Menu menu) 
		{
		    	// TODO Auto-generated method stub	    	
			new MenuInflater(getApplicationContext()).inflate(R.menu.restore_option_menu, menu);
			return super.onCreateOptionsMenu(menu);
		}

		public boolean onOptionsItemSelected(MenuItem item) 
		{
		    	// TODO Auto-generated method stub
		    switch(item.getItemId())
		    {
		    	case R.id.menu_restore_File: 		
		    		// duyet mang file va lay nhung file nao duoc check 
		    		CheckInternet chkI= new CheckInternet(context);
	    	        if(chkI.checkStatus().equals(false))
	    			{
	    				showAlertDialog("Thông Báo !", "Không có kết nối internet, vui lòng thử lại sau", new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							
							}
						});
	    			}
	    	        if(listFiles.isEmpty()){
	    	    		showToast("Danh sách trống!");
	    	    	} else if(numberOfItemSelected <= 0 ){
	    	    		showToast("Vui lòng chọn tin nhắn cần phuc hoi!!");
	    	    	}else if (numberOfItemSelected > 1 )
	    	    	{
	    	    		showAlertDialog("Thông báo !", "Bạn chỉ phục hồi một tập tin ", new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
	    	    	}
	    	    	else
	    	    	{
	    	        //xu ly phục hoi tin nhắn 
	    	        showConfirmDialog("Thông Báo !","Bạn có muốn phục hồi tin nhắn này ", new OnClickListener() 
	    			{
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							new AsyncTask<Void, Void, Void>()
							{
								@Override
								protected void onPreExecute() {
									// TODO Auto-generated method stub
									super.onPreExecute();
									loadingSmsDialog.setMessage("Đang tải dữ liệu từ máy chủ");
									loadingSmsDialog.show();
								}	
								@Override
								protected Void doInBackground(Void... params) 
								{
									// TODO Auto-generated method stub
									try 
									{								
			                            Thread.sleep(1000);     
			                            //kiem tra file nao dc check 
			                            Log.d("listfile", String.valueOf(listFiles.size()));
			                            String urldownload = "http://"+getSetting("address")+"/ServerWeb/USERS/"+username+"/";
			                            for(int i=0;i<listFiles.size();i++)
			                            {
			                            	FileObject entry=flist.get(i);
			                            	
			                            	if(listFiles.get(i).getChecked()==true)
			                            	{
			                            		urldownload = urldownload + entry.getFileName();
			                            		Log.d("namefile", listFiles.get(i).getName());
			                            		Log.d("urldownload", urldownload);
//												restoreFromServer(entry.getPathFile(), entry.getFileName(), path);
												restoreFromServer(urldownload, entry.getFileName(), path);
												Log.d("path",path);
												WebService.writeUserLog(entry.getFileID(), 2, "phuc hoi tap tin sms tu may chu!");
												System.out.println("duong dan tap tin sms da phuc hoi:"+ flist.get(i).getPathFile());
												//xu ly giai ma file phuc hoi
												//lay ten file va duong dan file phuc hoi
												aes=new AESControl(username);
												
												String pathTemp=path+"/"+entry.getFileName();
												Log.d("pathtemp",pathTemp);										
												String output = pathTemp+".dec";
												
												Log.d("out",output);		
												aes.DecFile(pathTemp, output);
											
					                           // xu ly import vào 
												restoreSMSFromSdcard(output);
												
												File pathtemp_file= new File(pathTemp);
												pathtemp_file.delete();
												File temp= new File(output);
												temp.delete();
												
												
			                            	}
			                            }	
			                        } 
									catch (Exception e)
			                        {
			                            // TODO Auto-generated catch block
			                            e.printStackTrace();
			                        }
									return null;
								}
								@Override
								protected void onPostExecute(Void result) 
								{
									// TODO Auto-generated method stub
									loadingSmsDialog.dismiss();
									for(int j=0 ; j<listFiles.size() ; j++)
									{
										listFiles.get(j).setChecked(false);				
									}
									arrayAdapter.notifyDataSetChanged();
									numberOfItemSelected=0;
									showAlertDialog("Thông Báo ! ", "Phục Hồi Thành Công ", new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
											
										}
									});
									super.onPostExecute(result);
								}
							}.execute();
						}
	    			
					});
	    	    	}
	    	        return true;
		    	case R.id.menu_restore_Delete:
		    			// duyet mang file de xem file nào đc check
		    			// xong xóa file theo tên file
		    		if(listFiles.isEmpty())
		    		{
			    		showToast("Danh sách trống!");
			    	}
		    		else if(numberOfItemSelected <= 0 )
		    		{
			    		showToast("Vui lòng chọn tin nhắn cần xóa!!");
			    	}
		    		else if (numberOfItemSelected > 0 )
		    		{
						showConfirmDialog("Xác Nhận Xóa", "Bạn có chắc chắn muốn xóa?", new OnClickListener() {
							public void onClick(DialogInterface dialog, int which) 
							{
								new AsyncTask<Void, Void, Void>()
								{
									@Override
									protected void onPreExecute() {
										// TODO Auto-generated method stub
										loadingSmsDialog.setMessage("Đang xóa tập tin");
										loadingSmsDialog.show();
										super.onPreExecute();
									}
									@Override
									protected Void doInBackground(
											Void... params) {
										for(int i=0;i<listFiles.size(); i++){
											myFile mfile = listFiles.get(i);
											FileObject entry = flist.get(i);
											if(mfile.getChecked()){
												try {
													String msg = WebService.deleteFileById(entry.getFileID(), "xoa tap tin sms da sao luu len may chu");
													Log.d("delete", msg);
													if(msg.equals("1")){
														listFiles.remove(mfile);
														flist.remove(entry);
														i--;
														numberOfItemSelected --;
													}
												} catch (Exception e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
											}
										}
										// TODO Auto-generated method stub
										return null;
									}
									@Override
									protected void onPostExecute(Void result) {
										// TODO Auto-generated method stub
										super.onPostExecute(result);
										loadingSmsDialog.dismiss();
										arrayAdapter.notifyDataSetChanged();
										showAlertDialog("Thông Báo !", "Xóa Thành Công ", new OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												
												dialog.cancel();
											}
										});
									}
								}.execute();
								
								
								//showToast("đã xóa tập tin");
							}
						});
			    	}
			    	return true;
		    		
		    		
		    	case R.id.menu_restore_Logout:
		    			logOut();
		    			Intent intent = new Intent(SmsRestoreServerActivity.this, LoginActivity.class);
		    			startActivity(intent);
		    			this.finish();
		    		return true;		
		    			
		    }
		    return false;
		}   

	
//---------------các hàm xư lý khác ----------------------
   	private void countItemChecked() 
   	{
   		numberOfItemSelected = 0;
   		for (int i = 0; i < listFiles.size(); i++) 
   		{
   			if (listFiles.get(i).getChecked()) 
   			{
            numberOfItemSelected++;
   			}
   		}
   	}

   	public void convert(ArrayList<FileObject> list)
   	{
   		for(int i = 0;i<list.size(); i++)
   		{
   			Log.d("size", String.valueOf(list.get(i).getFileSize()));
   			listFiles.add(new myFile(list.get(i).getFileName(),list.get(i).getPathFile(),String.valueOf(list.get(i).getFileSize()), res.getDrawable(R.drawable.ic_file_selector)));
   		}
   	}
   	public void CheckButtonOnClick(View v)
   	{
   		CheckBox chk = (CheckBox) v;
   		int pos = listview.getPositionForView(v);
   		myFile file = arrayAdapter.getItem(pos);
   		file.setChecked(chk.isChecked());
   		numberOfItemSelected += chk.isChecked() ? 1 : -1;
   	}
   	
	private static void restoreFromServer(String url, String fileName, String path)
	{
		try{
			int lenght = 0;
			File file = new File(path,fileName);	
			FileOutputStream fos = new FileOutputStream(file);
			
			System.out.println("url download file: " + url);
			System.out.println("path save file : " + path);
			
			//doi tuong urlconnection
	        URL u = new URL(url);
	        URLConnection urlconn = u.openConnection();
	        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
	        httpconn.setRequestMethod("GET");
	        httpconn.setDoOutput(true);
	        httpconn.connect();
	        //lay ve doi tuong va dat trong inputStream
	        InputStream in = httpconn.getInputStream();
			lenght=httpconn.getContentLength();
								
			byte[] buffer = new byte[1024];
	        int len1 = 0;
	        long total = 0;

	        while ((len1 = in.read(buffer)) > 0) {
	        	
	            total += len1; 
	            fos.write(buffer, 0, len1);
	        }
	        fos.close();	        			
	        System.out.println("length file : " + file.length());
		}catch (Exception e) 
		{
			// TODO: handle exception
			Log.e("KQ1", e.toString());
		}
	}
	
public void restoreSMSFromSdcard(String pathFile)
{
	File file = new File(pathFile);
	FileReader fr;
	try {
		fr = new FileReader(file);
		listFileRestore=xStreamXML.smsfromXML(fr);
		if(!listFileRestore.isEmpty())
		{
			Log.d("tag", "list co du lieu");
		}	
		else 
			Log.d("tag", "list rong");
		ContentValues value= new ContentValues();
		for(int i=0;i<listFileRestore.size();i++)
		{
			//value.put("_id", listFileRestore.get(i).getID());
			value.put("thread_id", listFileRestore.get(i).getThreadID());
			value.put("address", listFileRestore.get(i).getSMSName());
			value.put("body", listFileRestore.get(i).getSMSBody());
			value.put("date", listFileRestore.get(i).getCurrent());
			value.put("type", listFileRestore.get(i).getType());
			value.put("protocol", listFileRestore.get(i).getProtocol());
		
			context.getContentResolver().insert(Uri.parse("content://sms/inbox"), value);
			
		}
		
		
		//showToast("Restores xong");
	} catch (Exception e) {
		// TODO Auto-generated catch block
	//	showToast("Lỗi trong lúc phục hồi");
		e.printStackTrace();
	}
	
	
}
}
